import { postJson } from '@/lib/request';

import type {
    GridOptions,
} from "@ag-grid-community/core";

import {
    createAndInitilalizeTable,
} from '@/components/table/lib';

import {
    tf,
} from '@/components/table/lib';

import type { GridApi } from '@ag-grid-community/core';

import { handleFileAction } from '@/lib/file';

export function createTable(
    url: string,
    table_elem: HTMLElement,
    additionalColumnDefs: GridOptions['columnDefs'] = [] // Default to empty array
) {
    // Define default column definitions
    const defaultColumnDefs: GridOptions['columnDefs'] = [
        {
            field: "filename",
            headerName: gettext("文件"),
            type: 'file_name',
            cellRendererParams: (params: any) => {
                return {
                    contentType: params.data.content_type,
                    iconClass: 'tw:size-4'
                }
            },
            minWidth: 200,
            flex: 1
        },
        {
            field: "file_size",
            headerName: gettext("文件大小"),
            type: 'file_size'
        },
        {
            ...tf("uploaded_at", "上传时间"),
            type: 'date'
        },
    ];

    // Combine default columns with any additional columns
    const mergedColumnDefs = [...defaultColumnDefs, ...(additionalColumnDefs || [])];

    return createAndInitilalizeTable(
        url,
        table_elem,
        {
            rowSelection: { 
                mode: 'multiRow' 
            },
            columnDefs: mergedColumnDefs,
            onCellClicked: (event) => {
                const data = event.data;
                handleFileAction(data.link, data.filename);
            },
        }
    );
}


export async function deleteSelectedFiles(gridApi: GridApi) {
    const selected_rows = gridApi.getSelectedNodes();
    const file_ids = selected_rows.map(node => node.data.uuid);

    if (file_ids.length === 0) {
        alert(gettext("没有需要删除的文件"));
        return;
    }

    try {
        await postJson('/api/media/delete', file_ids);

        alert(gettext("删除成功"));
        window.location.reload();
    } catch (error) {
        // Error already handled by request function
    }
}

export function setupPage(
    get_data_api_path: string,
    table_elem: HTMLElement,
    delete_selected_btn_elem: HTMLElement | null,
) {
    const gridApi = createTable(get_data_api_path, table_elem);

    delete_selected_btn_elem?.addEventListener("click", () => {
        deleteSelectedFiles(gridApi);
    });
}
